/**
 * 和普元同步数据
 * @author yanwl 
 * @date 2014-10-20
 */
package com.chnbst.bstyun.eos;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.chnbst.bstyun.core.common.DESUtil;
import com.chnbst.bstyun.core.common.HttpRequest;
import com.chnbst.bstyun.core.common.ReadProperties;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.model.pojo.Meal;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.Product;
import com.chnbst.bstyun.model.vo.MealProductVo;
import com.chnbst.bstyun.model.vo.UserVo;
import com.chnbst.bstyun.service.MealProductService;
import com.chnbst.bstyun.service.MealService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.ProductService;
import com.chnbst.bstyun.service.UserService;

@Component
public class Eos {
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private MealProductService mealProductService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ReadProperties read;
	@Autowired
	private MealService mealService;
	
	private final static Logger logger = LoggerFactory.getLogger(Eos.class);
	
	/**
	 * 购买成功后给普元同步套餐购买信息
	 */
	@SuppressWarnings("unchecked")
	public String sendMeal(Integer orderId) throws Exception {
		Order order = orderService.selectOrderByOrderId(orderId);
		UserVo user = userService.selectUserVoByUserId(order.getUserId());
		
		//查询套餐包含的产品
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("mealId", order.getMealId());
		map.put("start", 0);
		map.put("pageSize", Integer.MAX_VALUE);
		map.put("sortField", "mp.add_time");
		map.put("sortOrder", "asc");
		
		List<MealProductVo> mpv = mealProductService.selectMealProductVos(map);
		String appCode = "";
		for (MealProductVo mealProductVo : mpv) {
			appCode += mealProductVo.getProductNum()+",";
		}
		
		Meal meal = mealService.selectMealByMealId(order.getMealId());
		
		Integer amount = order.getUserNum();
		String expires = SignUtil.time2str(order.getOverTime(), "yyyy-MM-dd");
		
		String industry = user.getCompanyIndustryName();
		String scale = user.getCompanyScaleName();
		String userId = user.getUserEmail();
		String password = DESUtil.decrypt(user.getUserPassword());
		String orgName = user.getBelongCompanyName();
		String empName = user.getContactName();
		String email = user.getBoundEmail();
		String[] str = user.getCompanyDomainName().split("www.");
		String domain = str[1];
		String deptName = user.getCompanyDepartment();
		String phone = user.getPhone();
		String combo = meal.getMealName();
		String version = meal.getMealVersion();

		String params = "userId="+userId+"&password="+password+"&orgName="+orgName
					  + "&empName="+empName+"&email="+email+"&industry="+industry+"&scale="+scale
					  + "&domain="+domain+"&deptName="+deptName+"&appCode="+appCode+"&amount="+amount
					  +"&expires="+expires+"&phone="+phone+"&combo="+combo+"&version="+version;
		long startTime = System.currentTimeMillis();
		logger.info("套餐购买开始时间："+SignUtil.time2str(new Date(), "yyyy-MM-dd hh:mm:ss:SSS"));
//		String result = httpRequest.sendPost(read.getEosUrl()+"/com.primeton.zckt.zcktUtil.zcktAdd.biz.ext",params);
		String url = read.getZcktURL() + params;
		String friendUrl = read.getFirendURL()+"tenantid="+domain;
		String result = HttpRequest.sendHttpRequest(url,read.getEosLocalhost(),Integer.valueOf(read.getEosPort()));
		
		HttpRequest.sendHttpRequest(friendUrl,read.getMcLocalhost(),Integer.valueOf(read.getEosPort()));
		long endTime = System.currentTimeMillis();
		logger.info("套餐购买结束时间："+SignUtil.time2str(new Date(), "yyyy-MM-dd hh:mm:ss:SSS"));
		logger.info("套餐购买调用接口时间毫秒数："+(endTime-startTime));
		logger.info(result);
		 Map<String, Object> returnMap = new ObjectMapper().readValue(result, Map.class);
	     return (String) returnMap.get("isReturn");
	}
	
	/**
	 * 购买成功后给普元同步单个产品购买信息
	 */
	@SuppressWarnings("unchecked")
	public String sendProduct(Integer orderId) throws Exception {
		Order order = orderService.selectOrderByOrderId(orderId);
		UserVo user = userService.selectUserVoByUserId(order.getUserId());
		
		Product product = productService.selectProductByProductId(order.getNewProId());
		String appCode = product.getProductNum();
		
		String[] dataStr = order.getDataExtend().split("&");
		
		String amount = dataStr[1];
		String expires = dataStr[2];
		
		String[] str = user.getCompanyDomainName().split("www.");
		String domain = str[1];
		String params = "domain="+domain+"&appCode="+appCode+"&amount="+amount+"&expires="+expires;
		
		long startTime = System.currentTimeMillis();
		logger.info("增值服务购买开始时间："+SignUtil.time2str(new Date(), "yyyy-MM-dd hh:mm:ss:SSS"));
//		String result = httpRequest.sendPost(read.getEosUrl()+"/com.bst.sjtb.bstyun.imp.UserBstyunControl.userBstyunDomainApp.biz.ext",params);
		
		String portalUrl = read.getProtalURL()+ params;
		String defaultUrl = read.getDefaultURL()+ params;
		String isportal = HttpRequest.sendHttpRequest(portalUrl,read.getMcLocalhost(),Integer.valueOf(read.getEosPort()));
		String isdefault = HttpRequest.sendHttpRequest(defaultUrl,read.getMcLocalhost(),Integer.valueOf(read.getEosPort()));
		
		logger.info("portalUrl:"+portalUrl);
		logger.info("defaultUrl:"+defaultUrl);
		logger.info(isportal+"--"+isdefault);
		String result = "";
		if(isportal.contains("isReturn") || isportal.contains("exception") || isdefault.contains("isReturn") || isdefault.contains("exception")) {
			result = "数据同步请求异常";
		}else {
			Map<String, Object> returnMap1 = new ObjectMapper().readValue(isportal, Map.class);
			Map<String, Object> returnMap2 = new ObjectMapper().readValue(isdefault, Map.class);
			int res1 = (Integer) returnMap1.get("isportal");
			boolean res2 = (boolean) returnMap2.get("isdefault");
			
			if(res1 == 1 && res2) {
				result = "ok";
			}else {
				result = "exception";
			}
		}
		long endTime = System.currentTimeMillis();
		logger.info("增值服务购买结束时间："+SignUtil.time2str(new Date(), "yyyy-MM-dd hh:mm:ss:SSS"));
		logger.info("增值服务购买调用接口时间毫秒数："+(endTime-startTime));
		logger.info(result);
		return result;
	}
	
	/**
	 * 升级或者续费后给普元同步产品购买信息
	 */
	@SuppressWarnings("unchecked")
	public String sendProOrMeal(Integer orderId) throws Exception {
		Order order = orderService.selectOrderByOrderId(orderId);
		UserVo user = userService.selectUserVoByUserId(order.getUserId());
		String appCode = "";
		String amount = "";
		String expires = "";
		if(order.getNewProId() == null) {
			//查询套餐包含的产品
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("mealId", order.getMealId());
			map.put("start", 0);
			map.put("pageSize", Integer.MAX_VALUE);
			map.put("sortField", "mp.add_time");
			map.put("sortOrder", "asc");
			
			List<MealProductVo> mpv = mealProductService.selectMealProductVos(map);
			for (MealProductVo mealProductVo : mpv) {
				appCode += mealProductVo.getProductNum()+",";
			}
			
			amount = String.valueOf(order.getUserNum());
			expires = SignUtil.time2str(order.getOverTime(), "yyyy-MM-dd");
		}else {
			Product product = productService.selectProductByProductId(order.getNewProId());
			appCode = product.getProductNum();
			String[] dataStr = order.getDataExtend().split("&");
			amount = dataStr[1];
			expires = dataStr[2];
		}
		
		String[] str = user.getCompanyDomainName().split("www.");
		String domain = str[1];
		String params = "domain="+domain+"&appCode="+appCode+"&amount="+amount+"&expires="+expires;
		
		long startTime = System.currentTimeMillis();
		logger.info("升级或者续费开始时间："+SignUtil.time2str(new Date(), "yyyy-MM-dd hh:mm:ss:SSS"));
		
		String uporderUrl = read.getUporderURL()+params;
		String restr = HttpRequest.sendHttpRequest(uporderUrl,read.getMcLocalhost(),Integer.valueOf(read.getEosPort()));
		logger.info(uporderUrl);
		Map<String, Object> returnMap = new ObjectMapper().readValue(restr, Map.class);
		String result = (String) returnMap.get("isReturn");
		long endTime = System.currentTimeMillis();
		logger.info("升级或者续费结束时间："+SignUtil.time2str(new Date(), "yyyy-MM-dd hh:mm:ss:SSS"));
		logger.info("升级或者续费调用接口时间毫秒数："+(endTime-startTime));
		logger.info(result);
		return result;
	}
	
	/**
	 * 友情链接
	 */
	public void friend(String domain) throws Exception {
		String friendUrl = read.getFirendURL()+"tenantid="+domain;
		HttpRequest.sendHttpRequest(friendUrl,read.getMcLocalhost(),Integer.valueOf(read.getEosPort()));
	}
	
	/**
	 * 退单
	 */
	@SuppressWarnings("unchecked")
	public String chargeBack(String domainStr) throws Exception {
		String[] str = domainStr.split("www.");
		String domain = str[1];
		String chargeBackUrl = read.getChargeBackUrl()+"domain="+domain;
		logger.info(chargeBackUrl);
		long startTime = System.currentTimeMillis();
		logger.info("退单开始时间："+SignUtil.time2str(new Date(), "yyyy-MM-dd hh:mm:ss:SSS"));
//		String restr = HttpRequest.sendHttpRequest(chargeBackUrl,"172.16.3.161:8080",8080);
		String restr = HttpRequest.sendHttpRequest(chargeBackUrl,read.getMcLocalhost(),Integer.valueOf(read.getEosPort()));
		logger.info(restr);
		Map<String, Object> returnMap = new ObjectMapper().readValue(restr, Map.class);
		String result = (String) returnMap.get("isReturn");
		long endTime = System.currentTimeMillis();
		logger.info("退单结束时间："+SignUtil.time2str(new Date(), "yyyy-MM-dd hh:mm:ss:SSS"));
		logger.info("退单调用接口时间毫秒数："+(endTime-startTime));
		logger.info("返回结果："+result);
		return result;
	}
}
